package com.uestc.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.uestc.entity.Host;
import com.uestc.entity.UploadImageConfig;
import com.uestc.util.HttpUtil;
import com.uestc.util.JSONUtils;

@Controller
@RequestMapping("ueditor")
public class UEditorController {
	@Autowired
	private Host host;

	// ueditr后端配置
	@ResponseBody
	@RequestMapping(value = "config", headers = "Accept=application/json")
	public String config(@RequestParam("action") String action, @RequestParam("noCache") String nocache,
			HttpServletRequest request, HttpServletResponse response) {
		BufferedReader br =null;
		try {
			response.setContentType("application/json;charset=utf-8");
			Resource resource = new ClassPathResource("config.json");
			File file = resource.getFile();
			br = new BufferedReader(new FileReader(file));
			StringBuilder stringBuilder = new StringBuilder();
			String line;
			while ((line = br.readLine()) != null) {
				stringBuilder.append(line);
			}
			return stringBuilder.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}finally {
			if(br!=null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	// ueditr后端配置
	@ResponseBody
	@RequestMapping(value = "uploadimage")
	public String uploadimage(@RequestParam("action") String action, @RequestParam("upfile") MultipartFile file,
			HttpServletResponse response) {
		String path = HttpUtil.saveImage(file, host);
		UploadImageConfig config = new UploadImageConfig();
		config.setState("SUCCESS");
		config.setUrl(path);
		String picture = path.substring(path.lastIndexOf("/") + 1);
		config.setOriginal(picture);
		config.setTitle(picture);
		config.setType(HttpUtil.getExtName(path, ".".toCharArray()[0]));
		return JSONUtils.gsonToJson(config);
	}
}